<?php			
// wv-3.3 (c) 2008 by Alexander Klein, akx@gmx.net
// Data table
class WV_DataTable 
{
	private $users = array();           // user array
	private $displayDays = 0;           // table columns
	private $tableData = array();       // csv data
	private $days = array();            // current ISO dates
	private $dataValues = array();      // possible data values
	private $dataFileName = '';         // datafile name
	
	// Constructor
	function __construct($filename, $dDays, $dValues, $uList) 
	{
		// set object variables
		$this->dataFileName = $filename;
		$this->users = $uList;
		$this->dataValues = $dValues;
		$this->displayDays = $dDays;
		
		// run init functions
		$this->loadDays();
		$this->tidyDatabase();
		$this->readTableData();
	}

	// Load HTML table for Ajax response
	public function loadTable() 
	{	
		echo '<table id="WV_DataTable">';	
		
		// table header
		echo '<tr>';
		for ($i=0; $i<$this->displayDays+1; $i++) {
			if ($i == 0) {
				// first column should be empty
				echo '<th>&nbsp;</th>';
			}
			else {
				// select th class for weekend or working day
				if (intval(date('N', strtotime($this->days[$i]))) > 5 ) {
					echo '<th class="WV_Weekend">' . $this->formatDate($this->days[$i]) . '</th>';
				}
				else {
					echo '<th class="WV_WorkingDay">' . $this->formatDate($this->days[$i]) . '</th>';
				}
			}
		}
		echo '</tr>';	
		
		// table body
		for($i=0; $i<count($this->users); $i++) {
			echo '<tr>';
			for ($j=0; $j<$this->displayDays+1; $j++) {
				if ($j == 0) {
					// insert user names
					echo '<td class="WV_UserColumn">' . $this->users[$i] . '</td>';
				}
				else {
					// insert data
					echo '<td class="WV_DataColumn ' . $this->formatCellDataClass($this->getCellData($i, $j)) . '" id="' . $i . '-' . $j . '"' . 
					     ' onclick="WV_ToggleCellValue(this)"  onmouseover="WV_HighlightCell(this)"' .
					     ' onmouseout="WV_UnHighlightCell(this)">' . 
					     $this->formatCellData($this->getCellData($i, $j)) . '</td>';
				}
			}
			echo '</tr>';
		}					
		echo '</table>';
	}

	// switch cell value
	public function toggleCellValue ($cellId) 
	{
		// get row and column id from cell id
		$currentRow = strtok($cellId, '-');
		$currentColumn = strtok(' ');	
		$currentValue = $this->getCellData($currentRow, $currentColumn);
		
		// find next value in data values array
		$newValue = FALSE;	
		$valuePointer = reset($this->dataValues);
		while($valuePointer != $currentValue) {
			$valuePointer = next($this->dataValues);
		}
		if ($newValue = next($this->dataValues) === FALSE) {
			$newValue = $this->dataValues[0];
		}
		else {
			$newValue = current($this->dataValues);
		}
		
		// set new value
		$this->setRecordData($currentRow, $currentColumn, $newValue);
	}	
	
	// read data from csv file to tableData array
	private function readTableData() 
	{
		$dataFileHandler = fopen($this->dataFileName, 'r');
		$row = 0;	
		while (($data = fgetcsv($dataFileHandler, 1000, ",")) !== FALSE) {
	    $num = count($data);    
	    $this->tableData[$row] = array();
	    for ($c=0; $c < $num; $c++) {
	    		$this->tableData[$row][$c] = $data[$c];
	    }
	    $row++;
		}	
		fclose($dataFileHandler);	
	}
	
	// write data to csv file
	private function writeTableData() 
	{
		$dataFileHandler = fopen($this->dataFileName, 'w');	
		foreach ($this->tableData as $dataRecord) {
		  fputcsv($dataFileHandler, $dataRecord, ',');
		}	
		fclose($dataFileHandler);	
	}

	// load current days in ISO format
	private function loadDays() 
	{
		for ($i=0; $i<$this->displayDays+1; $i++) {
			array_push($this->days, date('Y-m-d', time() + ($i-1) * 60*60*24));
		}
	}

	// clean up database
	private function tidyDatabase() 
	{
		$this->readTableData();
		for ($i=0; $i<count($this->tableData); $i++) {		
			
			// delete data if date is not in current days array
			if (!in_array($this->tableData[$i][0], $this->days)) {
				unset($this->tableData[$i]);
			}
		}	
		$this->writeTableData();
	}

	// retrieve single cell data
	private function getCellData ($currentRow, $currentColumn) 
	{
		// search array
		$i = 0;
		while ($i < count($this->tableData)) {
			if ($this->tableData[$i][0] == $this->days[$currentColumn] && 
			    $this->tableData[$i][1] == $this->users[$currentRow]) {
				// if date and user matches, return data
				return $this->tableData[$i][2];
			}
			$i++;
		}
		return 0;
	}		
	
	// data formatter
	private function formatCellData ($cellData) 
	{
		/*
		// assign image to cell data
		switch ($cellData) {
			case '0':
				return ' ';
				break;
			case '1':
				return '<img src="weather_sun.png" alt="++">';
				break;
			case '2':
				return '<img src="weather_cloudy.png" alt="+">';
				break;
			case '3':
				return '<img src="weather_clouds.png" alt="-">';
				break;
			case '4':
				return '<img src="weather_rain.png" alt="--">';
				break;			
			case '5':
				return '<img src="weather_lightning.png" alt="---">';
				break;	
			default:
				return $cellData;
				break;
		}
		*/
		
		// return empty string
		return '';
	}	

	// cell formatter
	private function formatCellDataClass ($cellData) 
	{
		// assign background image to cell element
		return 'WV_CellData' + $cellData;

	}	
	
	// date formatter
	private function formatDate ($dateString) 
	{
		// crop day from ISO date
		$dateString = substr($dateString, 5);
		$monthString = strtok($dateString, '-');
		$dayString = strtok(' ');
		return $dayString;
	}	
	
	// save new data	
	private function setRecordData ($userId, $dayId, $newValue) 
	{
		// search data array
		$foundRecord = FALSE;
		$i = 0;
		while ($i < count($this->tableData)+1) {
			if ($this->tableData[$i][0] == $this->days[$dayId] && 
			    $this->tableData[$i][1] == $this->users[$userId]) {				
				// set new value and stop
				$this->tableData[$i][2] = $newValue;
				$foundRecord = TRUE;
				break;
			}
			$i++;
		}
		// if no appropriate data record found, create a new one
		if (!$foundRecord) {
			array_push($this->tableData, array($this->days[$dayId], $this->users[$userId], $newValue));
		}
		// save data to file
		$this->writeTableData();
	}
}
?>